<script>
	import Vue from 'vue'
	import _config from '@/config/index.js'
	import sha256_digest from '@/common/lib/sha256.js'
	import APPUpdate from "@/js_sdk/zhouWei-APPUpdate/APPUpdate/index.js";
	const bandSDK = uni.requireNativePlugin('BandSDK')
	const hgService = uni.requireNativePlugin("HG-Background");
	var bmap = require('@/common/lib/bmap-wx.min.js');
	var that;
	export default {
		onLaunch: function() {
			that = this;
			bandSDK.initClient(res=>{
			})
			bandSDK.registerBleStateChange(res=>{
				if(res==3){
					uni.showToast({
						"title":"手环已断开连接",
						"position":"bottom",
						"icon":"none"
					})
				}
			})
			plus.geolocation.getCurrentPosition(function(res){
				
			},function(err){
				if(err.code==1){
					uni.showToast({
						"title":"请打开GPS定位或检查应用定位权限",
						"position":"bottom",
						"icon":"none"
					})
				}else if(err.code==2){
					uni.showToast({
						"title":'定位失败，由于设备当前 GPS 状态差（或网络不畅）,建议持设备到相对开阔的露天场所再次尝试',
						"position":"bottom",
						"icon":"none"
					})
			
				}
			})
			var userInfo = uni.getStorageSync("userInfo")
			if(userInfo){
				setInterval(function(){
					// var BMap = new bmap.BMapWX({
					// 	ak: 'qBcf7xTtG21FmcPD8WBIcgnCr6H0EUn9' 
					// }); 
					// var fail = function(data) { 
					// 	uni.showModal({
					// 		title: '温馨提示',
					// 		showCancel:false,
					// 		content: '请打开位置服务收集位置信息(检查定位权限是否仅在应用内使用)',
					// 		confirmText:'去设置',
					// 		success: function (res) {
					// 			if (res.confirm) {
					// 				var main = plus.android.runtimeMainActivity();
					// 				var Intent = plus.android.importClass('android.content.Intent');
					// 				var Settings = plus.android.importClass('android.provider.Settings');
					// 				var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
					// 				main.startActivity(intent); // 打开系统设置GPS服务页面
					// 			}
					// 		}
					// 	})
					// }; 
					// var success = function(data) { 
					// 	var location = data.wxMarkerData[0]
						
					// 	location.terminalTime = formatDate(new Date())
					// 	uni.setStorageSync("location",location)
					// 	//上传到服务器
						
					// } 
					// // 发起regeocoding检索请求 
					// BMap.regeocoding({ 
					// 	fail: fail, 
					// 	success: success
					// });
					plus.geolocation.getCurrentPosition(function(res){
						var data = {
							latitude:res.coords.latitude,
							longitude:res.coords.longitude,
							address:'',
							desc:''
						}
						if(res.addresses==null||res.addresses==''||res.addresses==undefined){
							uni.request({
								url:`http://api.cellocation.com:81/regeo/?lat=${res.coords.latitude}&lon=${res.coords.longitude}&coord=gcj02&output=json`,
								success(result) {
									data.address = result.data.address
								}
							})
						}else{
							data.address = res.addresses
						}
						data.terminalTime = formatDate(new Date())
						uni.setStorageSync("location",data)
						//上传服务器
						data.startTime = new Date().getTime()
						data.userId = that.userInfo.PATIENT_ID
						uni.request({
							url:_config.SYNCDATA_BASE+"data-receive/uploadLocation",
							data:data,
							method:"POST",
							header:{
								authentication:"2833df6a-9384-483d-a0d6-25fd5f891cae"
							},
							success(res) {
								if(res.data=="receive successfully"){
								}
							}
						})
					},function(err){
						uni.showModal({
							title: '温馨提示',
							showCancel:false,
							content: err,
							confirmText:'去设置',
							success: function (res) {
								if (res.confirm) {
									var main = plus.android.runtimeMainActivity();
									var Intent = plus.android.importClass('android.content.Intent');
									var Settings = plus.android.importClass('android.provider.Settings');
									var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
									main.startActivity(intent); // 打开系统设置GPS服务页面
								}
							}
						})
					})
				},3600*60*30)
			}
			// 初始化系统
			this.goSetting()
			setInterval(this.initUnipush(),3600*23)
			this.initSystem()
			//检测版本更新
			APPUpdate()
		},
		onUnload() {
			hgService.closeService();
			bandSDK.unRegisterBleStateChange(res=>{
			})
		},
		onShow(){	
			if(uni.getStorageSync("userInfo")!=''){
				setTimeout(function(){
					that.$store.dispatch('WEBSOCKET_INIT');
				},500)
			}
			uni.setStorageSync("cid",plus.push.getClientInfo().clientid)
			var main = plus.android.runtimeMainActivity();
			var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
			var BAdapter = new BluetoothAdapter.getDefaultAdapter();
			if (!BAdapter.isEnabled()) {
				BAdapter.enable(); //启动蓝牙
			}
		},
		methods: {
			/**
			 * 初次启动提示用户开启通知权限
			 */
			goSetting(){
				var first = uni.getStorageSync("first")||false
				if(!first){
					uni.showModal({
						title:"通知权限开启提醒",
						content: '为了您更好的体验，建议您开启应用的锁屏通知、悬浮通知、桌面角标等。',
						showCancel: false,
						confrimText: '去设置',
						success: (res) => {
							if (res.confirm) {
								let main = plus.android.runtimeMainActivity();
								let intent;
								let pkName = main.getPackageName();
								let NotificationManagerCompat = plus.android.importClass("android.support.v4.app.NotificationManagerCompat");  
								let packageNames = NotificationManagerCompat.from(main);  
								let uid = main.getApplicationInfo().plusGetAttribute("uid");
								let Intent = plus.android.importClass('android.content.Intent');
								let Build = plus.android.importClass("android.os.Build");
								//android 8.0引导  
								if (Build.VERSION.SDK_INT >= 26) {
								   intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
								　　intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
								} else if (Build.VERSION.SDK_INT >= 21) { //android 5.0-7.0  
								　　intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
								　　intent.putExtra("app_package", pkName);
								　　intent.putExtra("app_uid", uid);
								} else { //(<21)其他--跳转到该应用管理的详情页
								　　let Settings = plus.android.importClass("android.provider.Settings");
								　　let Uri = plus.android.importClass("android.net.Uri");
								　　intent = new Intent();
								　　intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
								　　let uri = Uri.fromParts("package", main.getPackageName(), null);
								　　intent.setData(uri);
								}
								uni.setStorageSync("first",true)
								// 跳转到该应用的系统通知设置页  
								main.startActivity(intent);
							} else if (res.cancel) {
								
							}
						}
					})
				}
			},
			/***
			初始化个推
			***/
			initUnipush(){
				var timestamp = (new Date()).getTime();
				var sign = sha256_digest(_config.appkey+timestamp+_config.masterkey)
				uni.request({
					url:`https://restapi.getui.com/v2/${_config.appid}/auth`,
					method:"POST",
					data:{
					   "sign":sign,
					   "timestamp":timestamp,
					   "appkey":_config.appkey
				   },
				   success(res) {
						uni.setStorageSync("unipushToken",res.data.data.token)
				   }
				})
				
				// 监听消息事件，app不在运行
				 plus.push.addEventListener("receive", function(msg) {
					var data = JSON.parse(msg.payload)
					uni.navigateTo({
						url:`/pages/message/chat?username=${data.username}&nickname=${data.nickname}&avatar=${data.avatar}`
					})
				 }, false );
			},
			/**
			 * 初始化系统
			 */
			initSystem() {
				// 初始化录音管理器
				this.$store.commit('initRECORD')
				const self = this
				uni.getSystemInfo({
					success: function(e) {
						// #ifndef MP
						Vue.prototype.StatusBar = e.statusBarHeight;
						if (e.platform == 'android') {
							Vue.prototype.CustomBar = e.statusBarHeight + 50;
						} else {
							Vue.prototype.CustomBar = e.statusBarHeight + 45;
						};
						// #endif

						// #ifdef MP-WEIXIN
						Vue.prototype.StatusBar = e.statusBarHeight;
						let custom = wx.getMenuButtonBoundingClientRect();
						Vue.prototype.Custom = custom;
						Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
						// #endif		

						// #ifdef MP-ALIPAY
						Vue.prototype.StatusBar = e.statusBarHeight;
						Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
						// #endif
					}
				})
				if(uni.getStorageSync("role")==null||uni.getStorageSync("role")==undefined||uni.getStorageSync("role")==''){
					uni.setStorageSync("role","user")
				}
			}
		}
	}
</script>

<style>
	/*每个页面公共css */
	@import "@/common/free.css";
	@import "@/common/common.css";
	/* #ifndef APP-PLUS-NVUE */
	@import "@/common/free-icon.css";
	/* #endif */
	
	@import "common/css/uni.css";
	@import "colorui/main.css";
	@import "colorui/icon.css";
	@import "common/css/common.css";
	::-webkit-scrollbar {  
	    display: none;  
	    width: 0 !important;  
	    height: 0 !important;  
	    -webkit-appearance: none;  
	    background: transparent;  
	}
	image{will-change: transform}
</style>
